package services

import (
	"encoding/json"
	"fmt"
	"github.com/labstack/gommon/log"
	"law_case_api/dto"
	"law_case_api/models"
	"strings"
	"time"
)

type ContractService struct {
}

// CreateCustomerContract 创建客户合同信息
func (contract ContractService) CreateCustomerContract(wzjContractInfo models.WzjContractInfo) (bool, error) {
	tx := db.Begin()
	yearContractCount := int64(0)
	if wzjContractInfo.ContractCategory == "4" {
		if err := db.Table("wzj_db.wzj_contract_info").Where("contract_category =4 and FROM_UNIXTIME(create_date,'%Y') = DATE_FORMAT(NOW(),'%Y'); ").Count(&yearContractCount).Error; err != nil {
			return false, err
		}
	} else {
		if err := db.Table("wzj_db.wzj_contract_info").Where("contract_category !=4 and FROM_UNIXTIME(create_date,'%Y') = DATE_FORMAT(NOW(),'%Y'); ").Count(&yearContractCount).Error; err != nil {
			return false, err
		}
	}
	if time.Now().Year() == 2021 {
		yearContractCount += 19
	}
	wzjContractInfo.ContractCode = fmt.Sprintf("%s%s", wzjContractInfo.ContractCode, fmt.Sprintf("%06d", yearContractCount+1))
	wzjContractInfo.IsEnabled = 1 //默认有效
	if err := tx.Create(&wzjContractInfo).Error; err != nil {
		tx.Rollback()
		return false, err
	}
	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		return false, err
	}
	return true, nil
}

// UpdateCustomerContract 更新客户合同信息 -- 只更新合同名称，合同外部编号，合同签订时间，创建人
func (contract ContractService) UpdateCustomerContract(wzjContractInfo models.WzjContractInfo) (bool, error) {
	if err := db.
		Where("id=?", wzjContractInfo.Id).
		Select("customer_id,customer_name,contract_name,contract_category,contract_external_code,contract_sign_date,update_user_id,update_date").
		Updates(&wzjContractInfo).Error; err != nil {
		log.Error("UpdateCustomerContract--更新客户合同信息失败,失败原因：", err)
		return false, err

	}
	return true, nil
}

// GetContractById 根据合同id获取合同详情
func (contract ContractService) GetContractById(contractId int) (models.WzjContractInfo, error) {
	wzjContractInfo := models.WzjContractInfo{}
	if err := db.Where("id=?", contractId).Limit(1).Find(&wzjContractInfo).Error; err != nil {
		log.Error("GetContractById--根据合同id获取合同详情失败,失败原因：", err)
		return wzjContractInfo, err
	}
	return wzjContractInfo, nil
}

// GetContractListByCondition 根据登录人信息获取合同列表
func (contract ContractService) GetContractListByCondition(userId int, isLaw bool, contractListReq dto.ContractListReq) ([]models.WzjContractInfo, int64, error) {
	var wzjContractInfoList []models.WzjContractInfo
	tx := db.Where("1=1")
	if len(contractListReq.ContractName) > 0 {
		tx = tx.Where(" contract_name like ? ", "%"+contractListReq.ContractName+"%")
	}
	if !isLaw {
		tx = tx.Where("customer_id=?", userId)
	} else {
		law := LawService{}
		_law := models.WzjLawInfo{
			Id: int64(userId),
		}
		wzjLawInfo, _ := law.GetLawByCondition(_law)
		if wzjLawInfo.LawRole == 2 || wzjLawInfo.LawRole == 3 {
			tx = tx.Where("create_user_id=?", userId)
		}
	}
	dataCount := int64(0)
	if err := tx.Count(&dataCount).
		Select("id,customer_id,customer_name,contract_name,contract_code,contract_external_code,contract_sign_date,create_user_id,contract_status,create_date").
		Limit(int(contractListReq.PageSize)).Offset(int((contractListReq.PageIndex - 1) * contractListReq.PageSize)).
		Order("contract_sign_date desc").
		Find(&wzjContractInfoList).Error; err != nil {
		log.Error("GetContractListByCreateUserId--查询失败,失败原因：", err)
		return wzjContractInfoList, dataCount, err
	}
	return wzjContractInfoList, dataCount, nil
}

// JudgeCustomerContractStatus 审核合同状态
func (contract ContractService) JudgeCustomerContractStatus(wzjContractInfo models.WzjContractInfo) (bool, error) {
	if err := db.Where("id=?", wzjContractInfo.Id).
		Select("contract_status").
		Updates(&wzjContractInfo).Error; err != nil {
		log.Error("JudgeCustomerContractStatus--审核合同状态失败,失败原因：", err)
		return false, err
	}
	return true, nil
}

// GetCustomerContractForSelectByCustomer 根据当前登录人获取名下的所有客户信息
func (contract ContractService) GetCustomerContractForSelectByCustomer(customerId int) ([]models.SelectValue, error) {
	var list []models.SelectValue
	sql := "SELECT contract_code 'value',contract_name 'label' FROM wzj_db.wzj_contract_info WHERE customer_id = ?;"
	if err := db.Raw(sql, customerId).Find(&list).Error; err != nil {
		log.Error("GetCustomerContractForSelectByCustomer--根据当前登录人获取名下的所有客户信息失败,失败原因：", err)
		return list, err
	}
	return list, nil
}

// GetContractCountByCondition 根据客户id获取合同数量
func (contract ContractService) GetContractCountByCondition(customerIds []int64) map[int64]dto.ObjectCount {
	var objectCounts []dto.ObjectCount
	var objectCountMap = make(map[int64]dto.ObjectCount)
	customerIdsBytes, _ := json.Marshal(customerIds)
	sqlInStr := strings.Replace(strings.Replace(string(customerIdsBytes), "[", "", -1), "]", "", -1)
	sql := fmt.Sprintf(`SELECT customer_id object_id,COUNT(customer_id) object_count FROM wzj_db.wzj_contract_info 
		WHERE customer_id in(%s) GROUP BY customer_id`, sqlInStr)
	if err := db.Raw(sql).Find(&objectCounts).Error; err != nil {
		return objectCountMap
	}
	for _, v := range objectCounts {
		objectCountMap[v.ObjectId] = v
	}
	return objectCountMap
}
